package com.sunday.shoufen.ui.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.adapter.CommonAdapter;
import com.sunday.common.widgets.adapter.ViewHolder;
import com.sunday.common.widgets.pickerview.TimePickerView;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.shoufen.R;
import com.sunday.shoufen.base.BaseApp;
import com.sunday.shoufen.entity.Income;
import com.sunday.shoufen.entity.RecordDetail;
import com.sunday.shoufen.http.ApiClient;

import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/10/25.
 * 卡券余额
 */

public class MyCouponBalanceActivity extends BaseActivity {


    @Bind(R.id.btn_back)
    ImageView btnBack;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.my_total_score)
    TextView myTotalScore;
    @Bind(R.id.txt)
    TextView txt;
    @Bind(R.id.score_time)
    TextView scoreTime;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    private List<RecordDetail> dataSet = new ArrayList<>();
    private CommonAdapter<RecordDetail> adapter;
    private LinearLayoutManager layoutManager;
    private boolean isCanloadMore;
    private int lastVisibleItem;
    private int pageNo = 1;
    private long memberId;
    private String selectDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_coupon_balance);
        ButterKnife.bind(this);
        initView();
        getData();
    }

    private void initView() {
        memberId = BaseApp.getInstance().getMember().getId();
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());
        adapter = new CommonAdapter<RecordDetail>(mContext, R.layout.list_coupon_balance_item, dataSet) {
            @Override
            public void convert(ViewHolder holder, RecordDetail recordDetail) {
                bind(holder, recordDetail);
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
    }

    private void bind(ViewHolder holder, RecordDetail recordDetail) {
        TextView score = holder.getView(R.id.money);
        TextView time = holder.getView(R.id.time);
        TextView from = holder.getView(R.id.from);
        ImageView imgExpired = holder.getView(R.id.img_expired);

        score.setText(recordDetail.getAmount().setScale(2, RoundingMode.HALF_UP) + "");
        time.setText("有效期至" + recordDetail.getTime());
        from.setText(recordDetail.getMemo());
        switch (recordDetail.getStatus()) {
            case 0:
                imgExpired.setVisibility(View.GONE);
                break;
            case 1:
                break;
            case 2:
                break;
        }

    }

    private Income income;

    private void getData() {
        Call<ResultDO<Income>> call = ApiClient.getApiAdapter().myAssets(memberId, 4, 1);
        call.enqueue(new Callback<ResultDO<Income>>() {
            @Override
            public void onResponse(Call<ResultDO<Income>> call, Response<ResultDO<Income>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    income = response.body().getResult();
                    updateView();
                    getRecordDetail();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Income>> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private void updateView() {
        if (income == null) {
            return;
        }
        myTotalScore.setText(income.getTicketMoney().setScale(2, RoundingMode.HALF_UP) + "");
    }

    private void getRecordDetail() {
        Call<ResultDO<List<RecordDetail>>> call = ApiClient.getApiAdapter().recordDetail(memberId, 4, 1, pageNo, Constants.PAGE_SIZE, selectDate);
        call.enqueue(new Callback<ResultDO<List<RecordDetail>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<RecordDetail>>> call, Response<ResultDO<List<RecordDetail>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    dataSet.addAll(response.body().getResult());
                    if (response.body().getResult() != null && response.body().getResult().size() == Constants.PAGE_SIZE) {
                        pageNo++;
                        isCanloadMore = true;
                    } else {
                        isCanloadMore = false;
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<RecordDetail>>> call, Throwable t) {

            }
        });
    }

    private TimePickerView timePickerView;

    @OnClick({R.id.score_time})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.score_time:
                timePickerView = new TimePickerView(mContext, TimePickerView.Type.YEAR_MONTH);
                timePickerView.setTime(new Date());
                timePickerView.setCyclic(true);
                timePickerView.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE);
                        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM", Locale.CHINESE);
                        selectDate = sdf.format(date);
                        scoreTime.setText(sdf1.format(date));
                        pageNo = 1;
                        getRecordDetail();
                        timePickerView.dismiss();
                    }
                });
                timePickerView.show();
                break;
        }
    }


}
